import requests
from tqdm import tqdm

# Define the ohsome API endpoint for geometry data.
url = "https://api.ohsome.org/v1/elements/geometry"

# Define the bounding polygon for the Black Sea region.
# Format: <customID>:<lon1>,<lat1>,<lon2>,<lat2>,...,<lonN>,<latN>
# Here, "BlackSea" is our custom ID and the coordinates form a rectangle.
bpolys_coords = "BlackSea:27,39,27,47,45,47,45,39,27,39"

# Set up the parameters:
# - time: the snapshot date (Nov 2020)
# - filter: query only features where aeroway equals aerodrome (i.e., airports)
# - bpolys: our defined bounding polygon for the Black Sea region
params = {
    "time": "2024-11-01",
    "filter": "aeroway=aerodrome",
    "bpolys": bpolys_coords
}

# Make a streaming request so we can monitor download progress.
with requests.get(url, params=params, stream=True) as r:
    r.raise_for_status()  # This will raise an exception if the request failed.
    
    # Try to retrieve the total file size from the response headers.
    total_size = int(r.headers.get('content-length', 0))
    
    # Open a file in binary write mode to save the downloaded data.
    with open("airports_blacksea_2020-11.json", "wb") as f, tqdm(
            total=total_size, unit='B', unit_scale=True, desc="Downloading"
    ) as progress_bar:
        # Iterate over the response in chunks.
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:  # Filter out keep-alive chunks.
                f.write(chunk)
                progress_bar.update(len(chunk))

print("Download complete! The airport data has been saved to 'airports_blacksea_2020-11.json'.")
